﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;

namespace NewZealandCoffee.model
{
    public class IceMsg
    {
        private static IceMsg instance;
        private IceMsg() { }

        public static IceMsg Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new IceMsg();
                }
                return instance;
            }
        }
        #region IO通讯
        public bool AllBol = true;
        /// <summary>
        ///  IO的通讯返回数据
        /// </summary>
        private List<byte> buffer = new List<byte>();
        public static bool IsMsgError = true;
        string nostrs = "";
        public Thread All_thr;
        public bool isBql = true;
        public bool isover = true;
        public bool iserror = false;
        public bool isBQLQL = false;
        public void IOSerial_Thr()
        {
            try
            {
                var ddd = SerialPort.GetPortNames().ToList();
                if (!SerialPort.GetPortNames().ToList().Any(a => a.ToLower().Contains(IPorPortInfo.Instance.ZBPortName)))
                {
                    Thread.Sleep(1000);
                    IOSerial_Thr();
                }
                ICSerialPort.Instance.IceMachineConnect(IPorPortInfo.Instance.ZBPortName, 19200, "", 8, 1);//其他串口通讯
                ICSerialPort.Instance.serialPort.DataReceived += SerialPort_DataReceived;
                All_thr = new Thread(AllMessages);
                All_thr.IsBackground = true;
                All_thr.Start();
            }
            catch (Exception)
            {
                ICSerialPort.Instance.serialPort.DataReceived -= SerialPort_DataReceived;
                Thread.Sleep(150);
                IOSerial_Thr();
            }
        }
        /// <summary>
        /// PING 通 IP
        /// </summary>
        /// <param name="IP"></param>
        /// <returns></returns>
        public bool PingIP(string IP)
        {
            try
            {
                if (IP.Split('.').Count() < 4) return false;
                Ping pingSender = new Ping();
                PingReply reply = pingSender.Send(IP, 120);//第一个参数为ip地址，第二个参数为ping的时间
                if (reply.Status == IPStatus.Success)
                {
                    return true;
                }
                else
                {
                    //ping不通
                    return false;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        #region 控制屏

        //public void Msg(string btnName, string tag)
        //{
        //    try
        //    {
        //        IOMsg.Instance.AllBol = false;
        //        Thread.Sleep(150);
        //        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LOpenBulkPowerDown);
        //        Thread.Sleep(150);
        //        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LCloseBulkPowerDown);
        //        Thread.Sleep(150);
        //        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_PTBPE_Down);
        //        Thread.Sleep(150);
        //        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_XSN_Down);
        //        Thread.Sleep(150);
        //        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QDCX_Down);
        //        Thread.Sleep(150);
        //        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_Stop_Down);
        //        Thread.Sleep(150);
        //        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_ZTCX_Down);
        //        Thread.Sleep(150);
        //        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JXYXCX_Down);
        //        Thread.Sleep(150);
        //        switch (btnName)
        //        {
        //            case "DO1":
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.PushRod_UP_end);
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.PushRod_Down_end);
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.PushRod_UP_start);
        //                Thread.Sleep(150);
        //                IOMsg.Instance.AllBol = true;
        //                Thread.Sleep(150);
        //                tag = "1";
        //                while (!DiaitalBool.Instance.PushRodUP_Sel_Bol)
        //                {
        //                    Thread.Sleep(150);
        //                }
        //                IOMsg.Instance.AllBol = false;
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.PushRod_UP_end);
        //                break;
        //            case "DO2":
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.PushRod_UP_end);
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.PushRod_Down_end);
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.PushRod_Down_start);
        //                Thread.Sleep(150);
        //                IOMsg.Instance.AllBol = true;
        //                Thread.Sleep(150);
        //                tag = "1";
        //                while (!DiaitalBool.Instance.PushRodDown_Sel_Bol)
        //                {
        //                    Thread.Sleep(150);
        //                }
        //                IOMsg.Instance.AllBol = false;
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.PushRod_Down_end);
        //                break;
        //            case "DO3":
        //                if (tag == "0")
        //                    ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.BSG_Direction1_start);
        //                else
        //                    ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.BSG_Direction1_end);
        //                break;
        //            case "DO4":
        //                if (tag == "0")
        //                    ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.BSG_Direction2_start);
        //                else
        //                    ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.BSG_Direction2_end);
        //                break;
        //            case "DO5":
        //                if (tag == "0")
        //                    ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.Fructose1_start);
        //                else
        //                    ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.Fructose1_end);
        //                break;
        //            case "DO6":
        //                if (tag == "0")
        //                    ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.Fructose2_start);
        //                else
        //                    ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.Fructose2_end);
        //                break;
        //            case "DO7":
        //                if (tag == "0")
        //                    ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.Fructose3_start);
        //                else
        //                    ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.Fructose3_end);
        //                break;
        //            case "DO8":
        //                IPorPortInfo.Instance.SweetInit1 = Convert.ToInt32(tag);
        //                using (FileStream stream = File.Create(MainWindow.IPorPortUrl))
        //                {
        //                    stream.Close();
        //                    stream.Dispose();
        //                    IPorPortInfo porPortInfo1 = IPorPortInfo.Instance;
        //                    File.WriteAllText(MainWindow.IPorPortUrl, JsonConvert.SerializeObject(porPortInfo1));
        //                }
        //                break;
        //            case "DO9":
        //                IPorPortInfo.Instance.SweetInit2 = Convert.ToInt32(tag);
        //                using (FileStream stream = File.Create(MainWindow.IPorPortUrl))
        //                {
        //                    stream.Close();
        //                    stream.Dispose();
        //                    IPorPortInfo porPortInfo1 = IPorPortInfo.Instance;
        //                    File.WriteAllText(MainWindow.IPorPortUrl, JsonConvert.SerializeObject(porPortInfo1));
        //                }
        //                break;
        //            case "DO10":
        //                IPorPortInfo.Instance.SweetInit3 = Convert.ToInt32(tag);
        //                using (FileStream stream = File.Create(MainWindow.IPorPortUrl))
        //                {
        //                    stream.Close();
        //                    stream.Dispose();
        //                    IPorPortInfo porPortInfo1 = IPorPortInfo.Instance;
        //                    File.WriteAllText(MainWindow.IPorPortUrl, JsonConvert.SerializeObject(porPortInfo1));
        //                }
        //                break;
        //            case "DO11":
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.RobotPowerOn1_start);
        //                DigitalMsgBol.Instance.RobotPowerOn1_Bol = true;
        //                Thread.Sleep(150);
        //                while (true)
        //                {
        //                    RobotOperate.CX_kj();
        //                    if (RobotOperate.state.poweredOn == 1)
        //                    {
        //                        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.RobotPowerOn1_end);
        //                        Thread.Sleep(150);
        //                        break;
        //                    }
        //                    Thread.Sleep(10);
        //                }
        //                RobotMsg(true, false, false, false, false, false, false);
        //                break;
        //            case "DO12":
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_BJ);
        //                Thread.Sleep(150);
        //                RobotMsg(false, false, false, false, false, false, true);
        //                break;
        //            case "DO13":
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LOpenBulkPowerUP);
        //                Thread.Sleep(150);
        //                while (true)
        //                {
        //                    RobotOperate.CX_status();
        //                    if (RobotOperate.status.powered_on == 1)
        //                    {
        //                        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LOpenBulkPowerDown);
        //                        Thread.Sleep(150);
        //                        break;
        //                    }
        //                    Thread.Sleep(10);
        //                }
        //                RobotMsg(false, true, false, false, false, false, false);
        //                break;
        //            case "DO14":
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LCloseBulkPowerUP);
        //                Thread.Sleep(150);
        //                RobotBol = true;
        //                while (true)
        //                {
        //                    RobotOperate.CX_status();
        //                    if (RobotOperate.status.powered_on == 0)
        //                    {
        //                        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LCloseBulkPowerDown);
        //                        Thread.Sleep(150);
        //                        break;
        //                    }
        //                    Thread.Sleep(10);
        //                }
        //                RobotMsg(true, false, false, false, false, false, false);
        //                break;
        //            case "DO15":
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_PTBPE_UP);
        //                Thread.Sleep(150);
        //                RobotBol = false;
        //                while (true)
        //                {
        //                    RobotOperate.CX_status();
        //                    if (RobotOperate.status.enabled == 1)
        //                    {
        //                        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_PTBPE_Down);
        //                        Thread.Sleep(150);
        //                        break;
        //                    }
        //                    Thread.Sleep(10);
        //                }
        //                RobotMsg(false, false, true, false, false, false, false);
        //                break;
        //            case "DO16":
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_XSN_UP);
        //                Thread.Sleep(150);
        //                RobotBol = true;
        //                while (true)
        //                {
        //                    RobotOperate.CX_status();
        //                    if (RobotOperate.status.enabled == 0)
        //                    {
        //                        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_XSN_Down);
        //                        Thread.Sleep(150);
        //                        break;
        //                    }
        //                    Thread.Sleep(10);
        //                }
        //                RobotMsg(false, true, false, false, false, false, false);
        //                break;
        //            case "DO17":
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QDCX_UP);
        //                Thread.Sleep(150);
        //                while (true)
        //                {
        //                    RobotOperate.CX_Start();
        //                    if (RobotOperate.pstatus == JKTYPE.ProgramState.PROGRAM_RUNNING)
        //                    {
        //                        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_QDCX_Down);
        //                        Thread.Sleep(150);
        //                        break;
        //                    }
        //                    Thread.Sleep(10);
        //                }
        //                RobotMsg(false, false, false, true, false, false, false);
        //                break;
        //            case "DO18":
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_Stop_UP);
        //                Thread.Sleep(150);
        //                while (true)
        //                {
        //                    RobotOperate.CX_Start();
        //                    if (RobotOperate.pstatus == JKTYPE.ProgramState.PROGRAM_IDLE)
        //                    {
        //                        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_Stop_Down);
        //                        Thread.Sleep(150);
        //                        break;
        //                    }
        //                    Thread.Sleep(10);
        //                }
        //                RobotMsg(false, false, false, false, true, false, false);
        //                break;
        //            case "DO19":
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_ZTCX_UP);
        //                DigitalMsgBol.Instance.RobotPowerOn1_Bol = true;
        //                Thread.Sleep(150);
        //                RobotBol = false;
        //                while (true)
        //                {
        //                    RobotOperate.CX_Start();
        //                    if (RobotOperate.pstatus == JKTYPE.ProgramState.PROGRAM_PAUSED)
        //                    {
        //                        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_ZTCX_Down);
        //                        Thread.Sleep(150);
        //                        break;
        //                    }
        //                    Thread.Sleep(10);
        //                }
        //                RobotMsg(false, false, false, false, false, true, false);
        //                break;
        //            case "DO20":
        //                Thread.Sleep(150);
        //                ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JXYXCX_UP);
        //                DigitalMsgBol.Instance.RobotPowerOn1_Bol = true;
        //                Thread.Sleep(150);
        //                RobotBol = false;
        //                while (true)
        //                {
        //                    RobotOperate.CX_Start();
        //                    if (RobotOperate.pstatus == JKTYPE.ProgramState.PROGRAM_RUNNING)
        //                    {
        //                        ICSerialPort.Instance.SerialSend(DigitalMsg.Instance.LRobot_JXYXCX_Down);
        //                        Thread.Sleep(150);
        //                        break;
        //                    }
        //                    Thread.Sleep(10);
        //                }
        //                RobotMsg(false, false, false, true, false, false, false);
        //                break;
        //            default:
        //                break;
        //        }
        //        Console.WriteLine(btnName + " " + tag);
        //        iodelegate(btnName, tag == "1" ? "0" : "1");
        //        Thread.Sleep(150);
        //        IOMsg.Instance.AllBol = true;
        //    }
        //    catch (Exception)
        //    {
        //        return;
        //    }
        //}
        ///// <summary>
        ///// 机器人状态
        ///// </summary>
        ///// <param name="KJ">开机</param>
        ///// <param name="SD">上电</param>
        ///// <param name="SN">使能</param>
        ///// <param name="YX">运行</param>
        ///// <param name="TZ">停止</param>
        ///// <param name="ZT">暂停</param>
        ///// <param name="BJ">报警</param>
        //public void RobotMsg(bool KJ, bool SD, bool SN, bool YX, bool TZ, bool ZT, bool BJ)
        //{
        //    Robot_Bol.Instance.Robot_YKJ = KJ;
        //    Robot_Bol.Instance.Robot_SD = SD;
        //    Robot_Bol.Instance.Robot_SN = SN;
        //    Robot_Bol.Instance.Robot_YX = YX;
        //    Robot_Bol.Instance.Robot_TZ = TZ;
        //    Robot_Bol.Instance.Robot_ZT = ZT;
        //    Robot_Bol.Instance.Robot_BJ = BJ;
        //}
        #endregion
        public void AllMessages()
        {
            try
            {
                while (true)
                {
                    // Console.WriteLine(AllBol + "chaxun");
                    try
                    {
                        if (AllBol)
                        {
                            Thread.Sleep(500);
                            ICSerialPort.Instance.SerialSend(IceMsgbool.Instance.IceType);
                            Thread.Sleep(500);
                            ICSerialPort.Instance.SerialSend(IceMsgbool.Instance.IceWuliao);
                            Thread.Sleep(500);
                        }
                        else
                            Thread.Sleep(1000);

                    }
                    catch (Exception)
                    {
                    }
                }
            }
            catch (Exception)
            {
                return;
            }
        }
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                byte[] result = new byte[ICSerialPort.Instance.serialPort.BytesToRead];
                ICSerialPort.Instance.serialPort.Read(result, 0, ICSerialPort.Instance.serialPort.BytesToRead);
                buffer.AddRange(result);
                string str = "";// $"{DateTime.Now}：\n";
                                //判断读写模式
                if (buffer.Count > 0x03)
                    str += $"{Encoding.ASCII.GetString(result)}";
                for (int i = 0; i < result.Length; i++)
                {
                    str += $"{result[i].ToString("X2")} ";
                }
                MsgShow(str);
                Thread.Sleep(10);
            }
            catch (Exception)
            {
                return;
            }
        }
        public void MsgShow(string str)
        {
            try
            {

                if (str.Contains("AB BA"))
                {
                    Console.WriteLine("接收  " + str);
                    if (CoffeeMakes.Instance.bol)
                    {
                        CoffeeMakes.Instance.bol = false;
                        File.WriteAllText(MainWindow.WarnPath + @"\接收1" + DateTime.Now.ToString("yyyyddMMHHmmssfff") + ".txt", JsonConvert.SerializeObject(str));
                    }
                    if (str.Length >= 30)
                    {
                        var dd = str.Split(' ');
                        if (dd.Count() > 8)
                        {
                            if (AllBol)
                            {
                                if (dd[5] == "03")
                                {
                                    isBql = dd[7] == "01" ? true : false;
                                    //if (!iserror && !isBql)
                                    //{
                                    //    iserror = true;
                                    //}
                                    //if (iserror && isBql)
                                    //{
                                    //    iserror = false;
                                    //    WuLiaoCoffeeSel.Instance.IsWLBol = true;
                                    //    WuLiaoCoffeeSel.Instance.IsICeMaterial = true;
                                    //    ClientList clientList = new ClientList();
                                    //    clientList.MsgBol = WuLiaoCoffeeSel.Instance;
                                    //    clientList.code = 2;
                                    //    SocketClients.Instance.client.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(clientList)));
                                    //    WuLiaoCoffeeSel.Instance.IsWLBol = false;
                                    //}
                                }
                                else if (dd[5] == "08")
                                {
                                    isBQLQL = dd[7] == "01" ? true : false;
                                }
                            }
                            else
                            {
                                if (CoffeeMakes.Instance.bol)
                                    File.WriteAllText(MainWindow.WarnPath + @"\接收" + DateTime.Now.ToString("yyyyddMMHHmmssfff") + ".txt", JsonConvert.SerializeObject(str));
                                isover = dd[7] == "01" ? true : false;
                            }

                        }
                    }
                }
                Console.WriteLine(DateTime.Now.ToString() + " " + isBQLQL.ToString());
                Console.WriteLine(DateTime.Now.ToString() + " " + isBql.ToString());
                if (WuLiaoCoffeeSel.Instance.IsICeMaterial != (isBQLQL && isBql))
                {
                    WuLiaoCoffeeSel.Instance.IsWLBol = true;
                    WuLiaoCoffeeSel.Instance.IsICeMaterial = (isBql && isBQLQL);
                    ClientList clientList = new ClientList();
                    clientList.MsgBol = WuLiaoCoffeeSel.Instance;
                    clientList.code = 2;
                    SocketClients.Instance.client.Send(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(clientList)));
                    WuLiaoCoffeeSel.Instance.IsWLBol = false;
                }
            }
            catch (Exception)
            {
                return;
            }
        }
        #endregion
    }
}
